<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="./css/bootstrap-theme.min.css"/>
	<link rel="stylesheet" type="text/css" href="./css/wangEditor.min.css"/>
    <link rel="stylesheet" type="text/css" href="./css/animate.min.css">
    <script src="./js/jquery.min.js"></script>
    <script src="../node_modules/tesseract.js/dist/tesseract.min.js"></script>
    <script src="./js/bootstrap.min.js"></script>
	<script src="./js/wangEditor.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="./js/uuid.min.js"></script>

    <style>
        .modal{
            z-index: 99999;
        }
        .modal-lg{
            width: 1400px;
        }
    </style>
</head>
<body>
<div class="container-fluid" style="margin-top: 2%;">
    <div class="row" style="display: flex;
    align-items: stretch;
    justify-content: stretch;">
        <div class="col-md-8">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    1.输入参数(可使用Ctrl+V粘贴截屏图片)
                </div>
                <div class="panel-body">
                    <div id="editor"></div>
                </div>
                <div class="footer text-right" style="padding: 2%;">
                    <button id="btnParse" class="btn btn-success">2.解析参数</button>
                </div>
            </div>
        </div>
        <div class="col-md-4" style="display: flex;flex-flow: column;align-items: stretch;justify-content: space-between;">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    3.正在解析的图片
                </div>
                <div class="panel-body" id="imgsView" style="height:250px;overflow: auto;">
                    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"></div>
                </div>
            </div>
            <div class="panel panel-primary">
                <div class="panel-heading">
                    4.已解析内容
                </div>
                <div class="panel-body">
                    <textarea name="" id="area" style="height: 88px;width: 100%;"></textarea>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12 text-center">
            <button id="modalBtn" style="width: 85%;height: 60px;" class="btn btn-primary animate__animated">查询答案</button>
        </div>
    </div>
</div>

<script>
    /*
    * 初始化富文本编辑器
    * */
	let E = window.wangEditor
	let editor = new E('#editor')
    // 自定义菜单配置
     editor.customConfig.menus = [
        'undo',  // 撤销
		'redo'  // 重复
    ]
    editor.customConfig.pasteFilterStyle = false
    editor.create()

    /*
    * 解析图片
    * */
    const recognize = async (files) => {
        $("#accordion").empty();
        for (let i = 0; i < files.length; i++) {
            let url = window.URL.createObjectURL(files[i])
            $("#accordion").append('<div class="panel panel-default">\n' +
                '                <div class="panel-heading" role="tab" id="headingOne">\n' +
                '                    <h4 class="panel-title">\n' +
                '                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse'+i+'" aria-expanded="true" aria-controls="collapseOne">\n' +
                '                            第'+(i+1)+'张图片\n' +
                '                        </a>\n' +
                '                    </h4>\n' +
                '                </div>\n' +
                '                <div id="collapse'+i+'" class="panel-collapse collapse '+(i===0?'in':'')+'" role="tabpanel" aria-labelledby="headingOne">\n' +
                '                    <div class="panel-body" style="padding-bottom: 0px;">\n' +
                '                        <div id="row'+i+'" class="row">\n' +
                '                            <img class="img-thumbnail" style="width: 90%;margin: 5%" src="'+url+'"/>\n' +
                '                            <div class="progress" style="margin-bottom: 0px;">\n' +
                '                                <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>\n' +
                '                            </div>\n' +
                '                        </div>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </div>')
            const worker = Tesseract.createWorker({
                workerPath: '../node_modules/tesseract.js/dist/worker.min.js',
                langPath: '../js',
                corePath: '../node_modules/tesseract.js-core/tesseract-core.wasm.js',
                logger: m => {
                    console.log(m)
                    if (m.status==="recognizing text"){
                        $("#row"+i).find(".progress-bar").width((m.progress*100).toFixed()+"%")
                        $("#row"+i).find(".progress-bar").html((m.progress*100).toFixed()+"%")
                    }
                    if (m.status==="recognizing text"&&m.progress===1){
                        editor.$textElem.attr('contenteditable', true)
                        $("#row"+i).find(".progress-bar").html("解析完成")
                    }
                },
            });
            await worker.load();
            await worker.loadLanguage('chi_sim');
            await worker.initialize('chi_sim');
            const { data: { text } } = await worker.recognize(url);
            console.log(text);
            $("#area").val($("#area").val()+text)
            await worker.terminate();
        }

    }

    /*给复制快捷键绑定自定义事件*/
    function bindPaste(){
        //定义变量存储获取的图片内容
        let blob;
        //获取body对象
        let body = document.getElementsByTagName("body");
        //定义body标签绑定的粘贴事件处理函数
        let fun=function(e){
            //获取clipboardData对象
            let data=e.clipboardData||window.clipboardData;
            //获取图片内容
            blob=data.items[0].getAsFile();
            //判断是不是图片，最好通过文件类型判断
            let isImg=(blob&&1)||-1;
            let reader=new FileReader();
            if(isImg>=0){
                //将文件读取为 DataURL
                reader.readAsDataURL(blob);
            }
            //文件读取完成时触发
            reader.onload=function(event){
                //获取base64流
                let base64_str=event.target.result;
                //div中的img标签src属性赋值，可以直接展示图片
                editor.txt.append('<img class="img-thumbnail" src="'+base64_str+'" />')
            }
        }
        //通过body标签绑定粘贴事件，注意有些标签绑定粘贴事件可能出错
        body[0].removeEventListener('paste',fun);
        body[0].addEventListener('paste',fun);
    }
    bindPaste()

    /*
    * 解析按钮点击事件
    * */
    $("#btnParse").off().on("click",function (){
        $("#area").val("");
        let files = []
        var imgs = $("<div>"+editor.txt.html()+"</div>").find("img");
        $("#area").val(editor.txt.text())
        for (let i = 0; i < imgs.length; i++) {
            let img = imgs[i]
            let src = img.getAttribute("src")
            let name = uuid.v4()
            let file = dataURLtoFile(src,name)
            files.push(file)
        }
        if (files.length>0){
            editor.$textElem.attr('contenteditable', false)
            recognize(files);
        }
    });

	/*工具方法，图片url转文件*/
    function dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }

    /*查询按钮事件*/
    $("#modalBtn").off().on("click",function (){
        window.open("https://www.shangxueba.com/ask/search?key="+encodeURIComponent($("#area").val()))
    })
    $("#modalBtn").hover(function(){
        $("#modalBtn").toggleClass("animate__pulse");
    });

</script>
</body>
</html>